<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>{{ categoryName || '全部' }}课程</span>
        <div class="extra">
          <el-button @click="goBack">返回首页</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline class="search-form">
      <el-form-item label="搜索：">
        <el-input v-model="keyword" placeholder="请输入搜索关键词" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchLessons">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="lessons.length === 0" class="empty-container">
      <el-empty description="暂无课程" />
    </div>

    <!-- 课程卡片列表 -->
    <div v-else class="lesson-grid">
      <el-card 
        v-for="lesson in lessons" 
        :key="lesson.id" 
        class="lesson-card"
        @click="showLessonDetail(lesson)"
      >
        <div class="lesson-cover">
          <img :src="lesson.coverImg" :alt="lesson.title">
          <div class="play-icon">
            <el-icon><VideoPlay /></el-icon>
          </div>
        </div>
        <div class="lesson-info">
          <h3 class="lesson-title">{{ lesson.title }}</h3>
          <div class="lesson-meta">
            <span>{{ lesson.categoryName }}</span>
            <span>{{ lesson.createUserName }}</span>
          </div>
          <div class="lesson-stats">
            <span class="stat-item">
              <el-icon><Collection /></el-icon>
              {{ lesson.likeCount || 0 }}
            </span>
            <span class="stat-item">
              <el-icon><Star /></el-icon>
              {{ lesson.favoriteCount || 0 }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[6, 12, 24, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 视频详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="currentLesson.title" width="70%" destroy-on-close>
      <template v-if="currentLesson">
        <div class="video-detail">
          <div class="detail-meta">
            <span>分类：{{ currentLesson.categoryName }}</span>
            <span>作者：{{ currentLesson.createUserName }}</span>
            <span v-if="currentLesson.createTime">发布时间：{{ currentLesson.createTime }}</span>
          </div>
          <div class="video-player-container">
            <video 
              ref="videoPlayer" 
              controls 
              class="video-player" 
              :src="currentLesson.videoUrl"
              @ended="videoEnded"
            ></video>
          </div>
          <div class="detail-content" v-if="currentLesson.content" v-html="currentLesson.content"></div>
          
          <div class="action-buttons">
            <el-button 
              :type="isLiked ? 'danger' : 'default'" 
              @click="toggleLike"
            >
              <el-icon><Collection /></el-icon>
              {{ isLiked ? '已点赞' : '点赞' }} ({{ likeCount }})
            </el-button>
            <el-button 
              :type="isFavorited ? 'warning' : 'default'" 
              @click="toggleFavorite"
            >
              <el-icon><Star /></el-icon>
              {{ isFavorited ? '已收藏' : '收藏' }} ({{ favoriteCount }})
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { VideoPlay, Collection, Star } from '@element-plus/icons-vue'
import { 
  lessonListService, 
  lessonLikeService,
  lessonUnlikeService,
  lessonFavoriteService,
  lessonUnfavoriteService,
  getLessonLikeStatusService,
  getLessonFavoriteStatusService,
  getLessonLikeCountService,
  getLessonFavoriteCountService
} from '@/api/lesson.js'

const route = useRoute()
const router = useRouter()

// 从路由参数中获取分类ID和名称
const categoryId = computed(() => route.query.categoryId)
const categoryName = computed(() => route.query.categoryName)

// 课程列表数据
const lessons = ref([])
const loading = ref(false)
const keyword = ref('')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 视频详情对话框
const dialogVisible = ref(false)
const currentLesson = ref({})
const videoPlayer = ref(null)

// 点赞和收藏状态
const isLiked = ref(false)
const isFavorited = ref(false)
const likeCount = ref(0)
const favoriteCount = ref(0)

// 获取课程列表
const fetchLessons = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      categoryId: categoryId.value || null,
      keyword: keyword.value || '',
      state: '已发布' // 只显示已发布的课程
    }
    
    const result = await lessonListService(params)
    
    if (result.code === 0 && result.data) {
      lessons.value = result.data.items || []
      total.value = result.data.total || 0
      
      if (lessons.value.length === 0 && currentPage.value > 1) {
        currentPage.value = 1
        fetchLessons()
      }
    } else {
      ElMessage.error(result.msg || '获取课程列表失败')
      lessons.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
    lessons.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置搜索条件
const resetSearch = () => {
  keyword.value = ''
  currentPage.value = 1
  fetchLessons()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchLessons()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchLessons()
}

// 显示课程详情
const showLessonDetail = async (lesson) => {
  currentLesson.value = lesson
  dialogVisible.value = true
  
  // 获取点赞和收藏状态
  await getLikeStatus(lesson.id)
  await getFavoriteStatus(lesson.id)
  
  // 获取点赞和收藏数量
  await getLikeCount(lesson.id)
  await getFavoriteCount(lesson.id)
  
  // 确保视频加载后自动播放
  setTimeout(() => {
    if (videoPlayer.value) {
      videoPlayer.value.play().catch(e => {
        console.warn('自动播放失败，可能需要用户交互:', e)
      })
    }
  }, 300)
}

// 视频播放结束
const videoEnded = () => {
  console.log('视频播放结束')
  // 可以在这里添加视频结束后的逻辑，比如推荐下一个视频
}

// 获取点赞状态
const getLikeStatus = async (lessonId) => {
  try {
    const result = await getLessonLikeStatusService(lessonId)
    if (result.code === 0) {
      isLiked.value = result.data
    }
  } catch (error) {
    console.error('获取点赞状态失败:', error)
  }
}

// 获取收藏状态
const getFavoriteStatus = async (lessonId) => {
  try {
    const result = await getLessonFavoriteStatusService(lessonId)
    if (result.code === 0) {
      isFavorited.value = result.data
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

// 获取点赞数量
const getLikeCount = async (lessonId) => {
  try {
    const result = await getLessonLikeCountService(lessonId)
    if (result.code === 0) {
      likeCount.value = result.data
    }
  } catch (error) {
    console.error('获取点赞数量失败:', error)
  }
}

// 获取收藏数量
const getFavoriteCount = async (lessonId) => {
  try {
    const result = await getLessonFavoriteCountService(lessonId)
    if (result.code === 0) {
      favoriteCount.value = result.data
    }
  } catch (error) {
    console.error('获取收藏数量失败:', error)
  }
}

// 点赞/取消点赞课程
const toggleLike = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isLiked.value) {
      // 取消点赞
      const result = await lessonUnlikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = false
        likeCount.value = Math.max(0, likeCount.value - 1)
        ElMessage.success('取消点赞成功')
      } else {
        ElMessage.error(result.msg || '取消点赞失败')
      }
    } else {
      // 点赞
      const result = await lessonLikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = true
        likeCount.value += 1
        ElMessage.success('点赞成功')
      } else {
        ElMessage.error(result.msg || '点赞失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 收藏/取消收藏课程
const toggleFavorite = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isFavorited.value) {
      // 取消收藏
      const result = await lessonUnfavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = false
        favoriteCount.value = Math.max(0, favoriteCount.value - 1)
        ElMessage.success('取消收藏成功')
      } else {
        ElMessage.error(result.msg || '取消收藏失败')
      }
    } else {
      // 收藏
      const result = await lessonFavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = true
        favoriteCount.value += 1
        ElMessage.success('收藏成功')
      } else {
        ElMessage.error(result.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 组件挂载时获取课程列表
onMounted(() => {
  fetchLessons()
})
</script>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-form {
  margin-bottom: 20px;
}

.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.lesson-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;
  height: 100%;
}

.lesson-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.lesson-cover {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.lesson-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 24px;
  opacity: 0.8;
  transition: opacity 0.3s, transform 0.3s;
}

.lesson-card:hover .play-icon {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1.1);
}

.lesson-info {
  padding: 12px;
}

.lesson-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.lesson-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
}

.lesson-stats {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.loading-container {
  padding: 20px 0;
}

.empty-container {
  padding: 40px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.video-detail .detail-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.video-detail .video-player-container {
  margin-bottom: 20px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

.video-player {
  width: 100%;
  max-height: 70vh;
}

.video-detail .detail-content {
  line-height: 1.6;
  color: #303133;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}
</style> 